from unittest import result
from fn import vis_frame
from Utils import base64_to_image, image_to_base64, list_to_tensor, str_to_tensor
import cv2
import requests
import json


def test_alphapose_image():
    cap = cv2.VideoCapture('/home/primer/video/test2.mp4')
    while True:
        ret, frame = cap.read()
        if frame is None:
            break
        encoded_string = image_to_base64(frame)
        url = "http://0.0.0.0:8080/"
        data = json.dumps({'image': encoded_string})
        r = requests.post(url=url, json=data)  # 直接把字典传给 requests.post() 的 json 参数
        string2 = r.text
        img = base64_to_image(string2)
        # print(img)
        cv2.imshow('demo', img)


def vis_frame_from_str_result(str_result, frame):
    result = eval(str_result)
    for human in result:
        human['keypoints'] = list_to_tensor(human['keypoints'])
        human['kp_score'] = list_to_tensor(human['kp_score'])
        human['proposal_score'] = list_to_tensor(human['proposal_score'])

    result = {
        'imgname': frame,
        'result': result
    }

    img = vis_frame(frame, result)
    return img


def test_alphapose_coordinate():
    cap = cv2.VideoCapture('/home/primer/video/test2.mp4')
    while True:
        ret, frame = cap.read()
        if frame is None:
            break
        encoded_string = image_to_base64(frame)

        url = "http://0.0.0.0:8080/"
        data = json.dumps({'image': encoded_string})

        r = requests.post(url=url, json=data)  # 直接把字典传给 requests.post() 的 json 参数
        tmp_string = r.text

        if tmp_string == 'None':
            cv2.imshow('demo', frame)
            continue

        else:
            img = vis_frame_from_str_result(tmp_string)
            cv2.imshow('demo', img)


def send_image():
    frame = cv2.imread('/home/primer/image/test.jpg')
    encoded_string = image_to_base64(frame)
    url = "http://0.0.0.0:8080/"
    data = json.dumps({'image': encoded_string})
    r = requests.post(url=url, json=data)  # 直接把字典传给 requests.post() 的 json 参数
    tmp_string = r.text
    if tmp_string == 'None':
        cv2.imshow('demo', frame)
        cv2.waitKey(3000)
        return

    with open('result_data.txt', 'w') as f:
        f.write(tmp_string)

    result = eval(tmp_string)
    for human in result:
        human['keypoints'] = list_to_tensor(human['keypoints'])
        human['kp_score'] = list_to_tensor(human['kp_score'])
        human['proposal_score'] = list_to_tensor(human['proposal_score'])

    result = {
        'imgname': frame,
        'result': result
    }
    print(result)
    img = vis_frame(frame, result)
    cv2.imshow('demo', img)
    cv2.waitKey(3000)


if __name__ == '__main__':
    # test_alphapose_coordinate()
    send_image()
